/**
 * create by Alec
 */
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { Modal, RefreshControl, ListView, List } from "@ali/ding-ui";
import { mid2Url } from "@ali/ding-mediaid";

// style
import "./index.less";

// compoents
import DDAvatar from "../../components/Avatar/";
import { setTitle, setRight, confirm, toast, openLink } from "../../utils/dingtalk.js";

// actions
import {
  fetchPendingLeave,
  deleteList
} from "../../actions/pendingLeave/index.js";

const mapper = {
  "1": "未发起离职交接",
  "2": "离职交接完成",
  "3": "离职交接中"
};

const PAGE_SIZE = 15;

const Item = List.Item;
const Brief = Item.Brief;

const mapStateToProps = () => ({});
const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(
    {
      dispatch,
      fetchPendingLeave,
      deleteList
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Pending extends Component {
  static defaultProps = {
    finish: {}
  };
  //propTypes 验证
  static propTypes = {
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      fetchPendingLeave: PropTypes.func,
      deleteList: PropTypes.func
    }).isRequired
  };
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2
    });
    this.state = {
      dataSource,
      isLoading: true,
      refreshing: false,
      height: document.body.clientHeight,

      pageIndex: 0,
      hasMore: false,
      data: [],
      total: "",
      prePage: 1
    };

    setRight({
      show: false
    });
    setTitle({
      title: "待离职员工"
    });
  }
  componentWillUpdate() {
    setTitle({
      title: "待离职员工"
    });
  }
  componentDidMount() {
    setTitle({
      title: "待离职员工"
    });
  }
  /**
   * 进入页面加载初始列表
   * */
  componentWillMount() {
    this.getPendingLeaveList(1);
    this.setState({ pageIndex: 1 });
  }

  /**
     * 获取待离职列表数据
     * @param {*页码} pageNum 
     */
  getPendingLeaveList = pageNum => {
    this.props.actions
      .fetchPendingLeave({
        page: pageNum,
        pageSize: PAGE_SIZE
      })
      .then(res => {
        if (res.success) {
          const data = [...this.state.data, ...res.result.data];
          this.setState({
            dataSource: this.state.dataSource.cloneWithRows(data),
            hasMore: res.result.hasMore,
            isLoading: false,
            total: res.result.total,
            data
          });
        }
      });
  };

  /**
    * 滚动加载更多
    * */
  onEndReached = () => {
    if (this.state.isLoading) {
      return;
    }
    if (!this.state.hasMore) {
      return;
    }
    const nextPage = this.state.pageIndex + 1;
    if (this.state.prePage !== nextPage) {
      this.state.prePage = nextPage;
      this.setState(
        {
          isLoading: true,
          pageIndex: nextPage,
          prePage: nextPage
        },
        () => {
          this.getPendingLeaveList(nextPage);
        }
      );
    }
  };

  /**
    * 顶部下拉刷新页面(use html body as a scroll container.)
    * 清零后去加载列表
    * setTimeout用于加载显示顶部刷新的loading
    * */
  onRefresh = () => {
    this.setState({ refreshing: true });
    this.state.prePage = 1;
    setTimeout(() => {
      this.setState(
        {
          dataSource: this.state.dataSource.cloneWithRows([]),
          refreshing: false,
          isLoading: true,
          pageIndex: 1,
          hasMore: false,
          data: [],
          isDeleteShow: false
        },
        () => {
          this.getPendingLeaveList(1);
        }
      );
    }, 1000);
  };

  /**
   * 删除操作
   * @param {*删除的用户ID} user 
   */
  deleteUser = userId => {
    console.log(`删除${userId}用户`); // eslint-disable-line
    this.props.actions.deleteList(userId).then(res => {
      if (res.success) {
        toast({icon: 'success', text:'操作成功'}); //没回调的地方
        this.setState(
          {
            dataSource: this.state.dataSource.cloneWithRows([]),
            refreshing: false,
            isLoading: true,
            pageIndex: 1,
            hasMore: false,
            data: [],
            isDeleteShow: false
          },
          () => {
            // this.getPendingLeaveList(1); // 删完人之后页面会卡在之前页面的位置
            window.location.reload(); // 删完人之后回到顶栏
          }
        );
      }
    });
  };

  /**
   * 确认员工离岗弹窗
   * @param {*用户ID} userId 
   */
  handleClick(e, userId) {
    e.stopPropagation();
    confirm({
      message: '确认离职后，会将员工从通讯录删除，员工档案将永久保存',
      buttonLabels: ['确认','取消'],
      cb: (res) => {
        if (res.buttonIndex === 0) {
          this.deleteUser(userId);
        } 
      }
    })
  }

  render() {
    const row = rowData => {
      return (
        <div className="list-wrap EMPlist">
          <List className="my-list">
            <Item
              extra={
                <div className="common-extra-btn">
                  <button onClick={e => this.handleClick(e, rowData.userId)}>
                    确认离职
                  </button>
                </div>
              }
              thumb={
                <DDAvatar
                  name={rowData.name}
                  size=""
                  avatar={
                    rowData.avatar &&
                    mid2Url(rowData.avatar, { imageSize: "thumb" })
                  }
                  className="growth-avatar-dd-avatar"
                  font=""
                />
              }
              multipleLine
              onClick={() =>
                (openLink(`?userId=${rowData.userId}#growth`))}
            >
              <h4>
                {rowData.name}
              </h4>

              <p className="dept">{rowData.dept}</p>

              <Brief>
                <p className="last-date">离职日期：{rowData.lastWorkDay}</p>

                <span
                  className={`type  pending-type-${rowData.handoverApproveStatus}`}
                >
                  {mapper[rowData.handoverApproveStatus]}
                </span>
              </Brief>
            </Item>
          </List>
        </div>
      );
    };
    return (
      <div>
        <div className="phone-border-fix"></div>
        {this.state.total !== 0 &&
          <ListView
            ref={el => (this.lv = el)}
            dataSource={this.state.dataSource}
            renderRow={row}
            pageSize={15}
            style={{
              height: this.state.height
            }}
            scrollerOptions={{ scrollbars: true }}
            refreshControl={
              <RefreshControl
                refreshing={this.state.refreshing}
                onRefresh={this.onRefresh}
              />
            }
            scrollRenderAheadDistance={500}
            scrollEventThrottle={200}
            onEndReached={this.onEndReached}
            onEndReachedThreshold={10}
            renderHeader={()=>{ 
              if (this.state.total !== 0) {
                return (
                  <div className="preJobList-title">
                    全部待离职员工 {this.state.total}人
                  </div>
                )
              }
            }}
          />}
          { this.state.total === 0 && !this.state.isLoading &&
            <div className="no-data">
              <img
                src="https://gw.alicdn.com/tfs/TB1xxCrmgMPMeJjy1XcXXXpppXa-174-198.png"
                alt=""
              />
              <p className="no-data-big-text">及时获悉离职申请，保障企业信息安全</p>
              <p className="no-data-small-text">当前暂无待离职员工</p>
            </div>
          }
      </div>
    );
  }
}
